import Header from '../../components/Header.vue';

export default {
	name: 'device',
	components: {
		Header
	},
	mounted: function() {
		this.findCompanyList();
		this.findSubCompany();
		this.findPlantformId();
		//保存下初始值
		this.defaultData = JSON.parse(JSON.stringify(this.addForm));
        this.user = JSON.parse(localStorage.getItem('userInfo'));
        console.log(this.user);

	},
	watch: {
		belongCompany: 'getBindUsers',
	},
	filters: {},
	methods: {
		getCompanyId: function() {
			this.searchGuid = '';
			this.type = '';
			// 公司编号
			this.companyId = localStorage.getItem("companyId");
			if (!this.companyId) {
				this.$router.push({
					path: '/home'
				});
			}

			var company = !localStorage.getItem("company") ? {} : JSON.parse(localStorage.getItem("company"));
			var resolutionTypeList = this.$getDictList("device_resolution");

			var resolutionTypes1 = [];
			resolutionTypeList.forEach(function(e) {
				if (parseInt(e.value) <= parseInt(company.resolution)) {
					resolutionTypes1.push(e);
				}
			});
			this.resolutionTypes = resolutionTypes1;
		},
		//分页size变化
		handleSizeChange: function(val) {
			this.pageInfo.pageSize = val;
			this.query(1);
		},
		//翻页
		handleCurrentChange: function(val) {
			this.query(parseInt(val));
		},
		// 分页查询
		query: function(pageNum) {
			this.loading = true;
			var params = {
				guid: this.searchGuid,
				companyId: this.belongCompany,
			};
			this.axios.hPost('/api/device?pageIndex=' + pageNum + '&pageSize=' + this.pageInfo.pageSize, params, (response) => {
				this.deviceData = response.list;
				this.pageInfo.totalNum = response.totalCount;
				this.pageInfo.currentPage = pageNum;
				this.loading = false;
			});
		},

		findCompanyList: function() {
			this.axios.hGet('/api/company/findAll', {}, (response) => {
				this.companyList = response;
				this.query(1);
			});
		},
		getBindUsers(cid) {
			console.log('企业ID'+cid)
			var params = {
				companyId: cid,
			};
			this.axios.hPost('/api/device/findUsers', params, (response) => {
				console.log('用户列表：'+response);
				var userSelections = [];
				response.forEach(function(e) {
					var item = {
						"key": e.id,
						"value": e.realName
					};
					if (cid === null) {
						userSelections.push(item);
					} else if (e.companyId === cid) {
						userSelections.push(item);
					}
				});
				this.userSelections = userSelections;
			});
		},
		// 显示增加窗口()
		showAddDialog: function() {
			this.getBindUsers(this.belongCompany);
			this.addFormTitle = this.$t('device.newDevice');
			this.saving = false;
			if (this.$refs['addForm']) {
				this.$refs['addForm'].resetFields();
				this.addForm = Object.assign(this.addForm, this.defaultData);
			}
			this.addFormVisible = true;
		},
		//修改窗口
		showModifyDialog: function(row) {
			this.getBindUsers(row.companyId);
			this.modFormTitle = this.$t('device.modifyDevice');
			this.saving = false;
			this.modFormVisible = true;
			if (this.$refs['addForm']) {
				this.$refs['addForm'].resetFields();
			}
			this.addForm.id = row.id;
			this.addForm.guid = row.guid;
			this.addForm.resolution = row.resolution;
			this.addForm.expireTime = row.expireTime;
			this.addForm.deviceUser = row.userName;

		},
		//保存或修改设备
		save: function() {
			this.saving = true;
			let url = '/api/device/save';
			this.$refs['addForm'].validate((valid) => {
				if (valid) {
					let params = {
						id: this.addForm.id,
						guid: this.addForm.guid,
						companyId: this.belongCompany,
						userId: this.addForm.deviceUser,
						checkCode: this.addForm.checkCode,
					};
					this.axios.hPost(url, params, (response) => {
                        console.log(response)
						if (response.success) {
							this.$message.success(response.msg);
							this.addFormVisible = false;
							this.modFormVisible = false;
							this.query(1);
						} else {
							this.$message.error(response.msg);
						}
						this.saving = false;
					});
				} else {
					this.saving = false;
					return false;
				}
			});
		},

		//删除设备
		deleteDevice: function(id) {
			this.$confirm(this.$t('message.DDDevice'), this.$t('standard.prompt'), {
				confirmButtonText: this.$t('standard.confirm'),
				cancelButtonText: this.$t('standard.cancel'),
				type: 'warning'
			}).then(() => {
				this.axios.hPost('/api/device/delete', {
					id: id
				}, (response) => {
					if (response.success) {
						this.$message.success(response.msg);
						this.addFormVisible = false;
						this.query(1);
					} else {
						this.$message.error(response.msg);
					}
				});
			});
		},
		isShow: function(id) {
			document.getElementById(id).style.display = "block";
		},
		isHiden: function(id) {
			document.getElementById(id).style.display = "none";
		},

		transToMinute: function(spendTime) {
			if (!spendTime) {
				return 0;
			}
			return parseFloat(spendTime / 60).toFixed(2);
		},

		over: function($event) {
			$event.currentTarget.className = 'device-row el-row device-on';
		},

		out: function($event) {
			$event.currentTarget.className = 'device-row el-row';
		},

		getCompanyName: function(companyId) {
			if (!companyId) {
				return '';
			}

			if (!this.companyList) {
				return '';
			}

			var companyName = "";
			while (companyId != 0) {
				this.companyList.find(item => {
					if (item.id == companyId) {
						if (!companyName) {
							companyName = item.companyName;
						} else {
							companyName = item.companyName + " - " + companyName;
						}

						companyId = item.parentId;
						return false;
					}
				});
			}
			return companyName;
		},
		formatNull: function(val) {
			if (val === null) {
				return '--'
			} else {
				return val
			}
		},
		findSubCompany() {
			this.axios.hPost('/api/device/getSubCompany', {
				companyId: this.belongCompany
			}, (response) => {
				var subCompanyList = [];
				response.forEach(function(e) {
					subCompanyList.push({
						'id': e.id,
						"companyName": e.companyName
					})
				});
				this.subCompanyList = subCompanyList
			});
		},
		findPlantformId() {
			this.axios.hPost('/api/device/plantformId', {}, (response) => {
				this.plantformId = response;
			});
		},
		formatValue(val) {
			return val ? val : this.$t('video.UnboundUsers');
		}


	},
	data: function() {
		return {

			//是否在加载标记
			loading: false,
			token: '',
			deviceData: [],
			noResult: false,
			loadingTxt: '',
			//存储分页数据
			pageInfo: {
				currentPage: 1,
				pageSize: 10,
				totalNum: 0
			},

			showDel: false,
			//搜索设备名称
			searchGuid: null,
			//搜索群组名称
			searchCompanyName: '',
			//表标题
			addFormTitle: '',
			modFormTitle: '',
			//增加的表
			addForm: {
				id: null,
				guid: '',
				resolution: '',
				expireTime: null,
				companyId: null,
				deviceUser: '',
				checkCode: null,
			},
			//默认数据
			defaultData: {},
			addFormVisible: false,
			modFormVisible: false,
			infoVisible: false,
			saving: false,
			typeId: '',
            user: {},
			type: '',

			addRules: {
				guid: [{
						required: true,
						message: this.$t('message.required'),
						trigger: 'blur'
					},
					{
						max: 20,
						message: this.$t('message.length20'),
						trigger: 'blur'
					},
					{
						pattern: /^([\u4e00-\u9FFFa-zA-Z0-9+\s]+)$/,
						message: this.$t('message.incorrectFormat'),
						trigger: 'blur'
					}
				],
				deviceUser: [{
					required: true,
					message: this.$t('message.fieldSelected'),
					trigger: 'blur'
				}],
				checkCode: [{
						required: true,
						message: this.$t('message.required'),
						trigger: 'blur'
					},
					{
						max: 20,
						message: this.$t('message.length20'),
						trigger: 'blur'
					}
				]

			},
			companyId: "",
			resolutionTypes: [],
			companyList: [],
			belongCompany: null,
			bindUser: null,
			userSelections: null,
			adminCompanyId: -99,
			subCompanyList: [],
			plantformId: null
		}
	}
}
